﻿using System;
using System.Collections.Generic;
using Jayden.Dll.Web.Exceptions;

namespace Jayden.Dll.Web.Helper
{
	public class TokenSet : List<string>
	{
		public TokenSet(string value) : this(value, ' ') { }
		public TokenSet(string value, params char[] separators)
		{
			if (!string.IsNullOrWhiteSpace(value))
			{
				string[] values = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
				AddRange(values);
			}
		}

		public delegate void TokenSetChanged(TokenSet set);
		public event TokenSetChanged Change;

		protected void FireChange()
		{
			if (Change != null)
				Change(this);
		}

		public new void Clear()
		{
			base.Clear();
			FireChange();
		}
		public new bool Add(string token) { return Add(token, true); }
		public bool Add(string token, bool checkContains)
		{
			if (!HtmlHelper.IsToken(token))
				throw new HtmlException("not a valid token : '{0}'.", token);
			if (checkContains && Contains(token))
				return false;
			base.Add(token);
			FireChange();
			return true;
		}
		public new bool Remove(string token)
		{
			bool result = base.Remove(token);
			if (result)
				FireChange();
			return result;
		}

		public override string ToString() { return ToString(" "); }
		public string ToString(string separator)
		{
			if (Count == 0)
				return null;
			return string.Join(separator, this);
		}
	}
}
